<template>
  <!-- 软件21H02 李垣辉 2021010511 -->
  <div class="login">
    <h1>登录</h1>
    <div class="form-item">
      <h3><span>*</span>手机号</h3>
      <el-input
        v-model="phone"
        placeholder="请输入手机号"
        style="width: 100%"
        @blur="validatePhone"
      />
      <div v-if="phoneError" class="error">{{ phoneError }}</div>
    </div>
    <div class="form-item">
      <h3><span>*</span>密码</h3>
      <el-input
        v-model="password"
        type="password"
        placeholder="请输入密码"
        style="width: 100%"
        @blur="validatePassword"
      />
      <div v-if="passwordError" class="error">{{ passwordError }}</div>
    </div>
    <el-button type="primary" plain @click="login" style="width: 100%">登录</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const phone = ref('')
const password = ref('')
const phoneError = ref('')
const passwordError = ref('')
const loggingIn = ref(false)

const validatePhone = () => {
  if (!/^\d{11}$/.test(phone.value)) {
    phoneError.value = '请输入有效的11位手机号'
  } else {
    phoneError.value = ''
  }
}

const validatePassword = () => {
  if (password.value.length < 6) {
    passwordError.value = '密码长度不能少于6位'
  } else {
    passwordError.value = ''
  }
}

const login = async () => {
  if (loggingIn.value) return
  loggingIn.value = true

  if (!/^\d{11}$/.test(phone.value) || password.value.length < 6) {
    ElMessage.error('请输入有效的手机号和密码')
    loggingIn.value = false
    return
  }

  try {
    const response = await axios.post('/api/login', {
      phone: phone.value,
      password: password.value
    })

    if (response.data.success) {
      // 假设后端返回了一个 token，你可以在这里保存它到 localStorage 或 Vuex
      localStorage.setItem('token', response.data.token)
      ElMessage.success('登录成功')
      // 跳转到首页或其他页面
      // router.push('/');
    } else {
      ElMessage.error(response.data.message || '登录失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后再试')
  } finally {
    loggingIn.value = false
  }
}
</script>

<style scoped>
.login {
  width: 300px;
  height: auto;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login h1 {
  text-align: center;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item h3 span {
  color: red;
}

.error {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

.el-button {
  width: 100%;
  background-color: skyblue;
}
</style>